package com.yylending.las.repay.repaydetail;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.Loader;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import com.yyfax.common.recyclerview.adapter.CommonAdapter;
import com.yyfax.common.recyclerview.adapter.MultiItemTypeAdapter;
import com.yyfax.common.recyclerview.base.ViewHolder;
import com.yyfax.common.recyclerview.listener.OnRefreshListener;
import com.yyfax.common.recyclerview.view.IRecyclerView;
import com.yyfax.common.recyclerview.wrapper.StatesAdapter;
import com.yyfax.common.recyclerview.wrapper.WrapperAdapter;
import com.yyfax.common.tools.DensityUtil;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yylending.las.R;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.common.utils.TimeUtils;
import com.yylending.las.StatIDSet;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.common.widgets.Divider;

import java.util.ArrayList;
import java.util.List;

/**
 * 多笔还款详情
 * Created by ying_he on 2017/7/8.<br>
 * Copyright  2017 www.yylending.com. All Rights Reserved.<br><br>
 */

public class MultiRepayDetailFragment extends BaseFragment implements StatesAdapter.RetryClickListener
		, OnRefreshListener, MultiItemTypeAdapter.OnItemClickListener {

	public static final int MIN_CLICK_DELAY_TIME = 1500;
	private static final String LOAN_STATUS_NORMAL = "0";
	private static final String LOAN_STATUS_OVERDUE = "1";
	public WrapperAdapter mWrapAdapter;
	@BindView(R.id.repay_list_rv)
	IRecyclerView mRepayListRv;
	private long mLastClickTime = 0;
	Unbinder mUnbind;
	private MultiItemTypeAdapter<RepayDetailListModel.Repay.RepayDetail> mAdapter;
	private List<RepayDetailListModel.Repay.RepayDetail> mRepayList = new ArrayList<>();
	private Divider mDivider;


	public static MultiRepayDetailFragment newInstance(ArrayList<RepayDetailListModel.Repay.RepayDetail> detail) {
		MultiRepayDetailFragment fragment = new MultiRepayDetailFragment();
		Bundle args = new Bundle();
		args.putParcelableArrayList(RepayDetailActivity.KEY_BUNDLE_ARG_REPAY_DETAIL_LIST, detail);
		fragment.setArguments(args);
		return fragment;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_multi_repay_detail, container, false);
		mUnbind = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initData();
	}

	private void initData() {
		mRepayList = getArguments().getParcelableArrayList(RepayDetailActivity.KEY_BUNDLE_ARG_REPAY_DETAIL_LIST);

		mRepayListRv.setLayoutManager(new GridLayoutManager(getActivity(), 1));
		mAdapter = new CommonAdapter<RepayDetailListModel.Repay.RepayDetail>(R.layout.adapter_item_multi_repay_detail, mRepayList, mRepayListRv.getItemViewDelegateManager()) {
			@Override
			protected void convert(ViewHolder holder, RepayDetailListModel.Repay.RepayDetail repay, int position) {
				holder.setText(R.id.loan_date_tv, TimeUtils.formatDateTimeDot(Long.valueOf(repay.loanDate)));
				holder.getView(R.id.flag_overdue_tv).setVisibility(TextUtils.equals(repay.loanStatus, LOAN_STATUS_OVERDUE) ? View.VISIBLE : View.GONE);
				holder.setText(R.id.loan_sum_tv, FormatUtils.getAmountWithSymbol(repay.loanAmount));
				holder.setText(R.id.repay_period_tv, String.format(getString(R.string.left_pay_term), repay.noPayTerm));
			}
		};
		mWrapAdapter = new WrapperAdapter(mAdapter, mRepayListRv, getActivity(), R.layout.state_view_no_data, R.layout.include_view_no_network);
		mDivider = new Divider(DensityUtil.dip2px(getActivity(), 10f), getResources().getColor(R.color.color_f1f3f7), false,
				0, 0, 0, DensityUtil.dip2px(getActivity(), 10f), 0);
		mRepayListRv.addItemDecoration(mDivider);
		mWrapAdapter.setOnItemClickListener(this);
		mWrapAdapter.setRetryClickListener(this);
		mRepayListRv.setAdapter(mWrapAdapter);
		mRepayListRv.setOnRefreshListener(this);
		mRepayListRv.setLoadMoreEnabled(false);
		mRepayListRv.setRefreshEnabled(false);

		if (mRepayList.size() <= 0) {
			// 必须删除,否则会出现多余的空隙.
			mRepayListRv.removeItemDecoration(mDivider);
			mWrapAdapter.setState(StatesAdapter.STATE_EMPTY);
		}
	}

	@Override
	public void onRefresh() {
		RepayDetailActivity.RequestRepayDetailListEvent event = new RepayDetailActivity.RequestRepayDetailListEvent();
		event.loanNo = "";
		EventAgent.post(event);
	}

	@Override
	public void onRetry() {

	}

	public void setData(ArrayList<RepayDetailListModel.Repay.RepayDetail> detail) {
		mRepayListRv.stopRefreshing();
		mRepayList.clear();
		mRepayList.addAll(detail);
		mWrapAdapter.refreshData(mRepayList);
	}

	@Override
	public void onItemClick(View view, ViewHolder holder, int position, int viewType) {
		position = holder.getAdapterPosition() - 1;
		// 防止过快重复点击
		long currentTime = System.currentTimeMillis();
		if (currentTime - mLastClickTime > MIN_CLICK_DELAY_TIME) {
			mLastClickTime = currentTime;
			//StatService.onEvent(getContext(), StatIDSet.EVENT_ID_CHECK_PAYMENT_DETAILS);
			RepayDetailActivity.RequestRepayDetailListEvent event = new RepayDetailActivity.RequestRepayDetailListEvent();
			event.loanNo = mRepayList.get(position).loanNo;
			event.type = "10";    //首页点击传的是首页获得的申请编号，type传20，多笔进入传的是申请编号type传10
			EventAgent.post(event);
		}
	}

	@Override
	public boolean onItemLongClick(View view, ViewHolder holder, int position, int viewType) {
		return false;
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		getActivity().runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mRepayListRv.hideFooterLoadMoreView();
				mRepayListRv.stopRefreshing();
				mWrapAdapter.setState(StatesAdapter.STATE_ERROR);
			}
		});
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {

	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return null;
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mUnbind.unbind();
	}
}
